﻿import { createRouter, createWebHistory } from 'vue-router'

// 路由配置
const routes = [
  // 登录和用户相关路由
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { 
      title: '登录',
      requiresAuth: false
    }
  },
  // 前台登录路由
  {
    path: '/front/login',
    name: 'FrontLogin',
    component: () => import('@/views/front/auth/FrontLogin.vue'),
    meta: { 
      title: '用户登录',
      requiresAuth: false
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/auth/Profile.vue'),
    meta: { 
      title: '个人信息',
      requiresAuth: true
    }
  },
  
  // 前台活动路由 - 使用FrontLayout布局
  {
    path: '/',
    component: () => import('@/views/front/layout/FrontLayout.vue'),
    meta: { 
      requiresAuth: false
    },
    children: [
      // 根路径直接显示活动列表
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/front/event/List.vue'),
        meta: { 
          title: '活动列表', 
          requiresAuth: false,
          allowAnonymous: true // 明确允许匿名访问
        }
      },
      {
        path: 'front/event/list',
        name: 'FrontEventList',
        component: () => import('@/views/front/event/List.vue'),
        meta: { 
          title: '活动列表', 
          requiresAuth: false
        }
      },
      {
        path: 'front/event/detail/:id',
        name: 'FrontEventDetail',
        component: () => import('@/views/front/event/Detail.vue'),
        meta: { 
          title: '活动详情', 
          requiresAuth: false
        }
      },
      {
        path: 'front/event/categories',
        name: 'FrontEventCategories',
        component: () => import('@/views/front/event/Categories.vue'),
        meta: { 
          title: '活动分类', 
          requiresAuth: false
        }
      },
      // 前台个人中心 - 需要前台登录
      {
        path: 'front/user/profile',
        name: 'FrontUserProfile',
        component: () => import('@/views/front/user/Profile.vue'),
        meta: { 
          title: '个人中心', 
          requiresAuth: false,
          requiresFrontAuth: true // 需要前台登录
        }
      },
      // 订单相关路由
      {
        path: 'front/order/create',
        name: 'FrontOrderCreate',
        component: () => import('@/views/front/order/CreateOrder.vue'),
        meta: { 
          title: '创建订单', 
          requiresAuth: false,
          requiresFrontAuth: true // 需要前台登录
        }
      },
      {
        path: 'front/order/pay',
        name: 'FrontOrderPay',
        component: () => import('@/views/front/order/PayOrder.vue'),
        meta: { 
          title: '订单支付', 
          requiresAuth: false,
          requiresFrontAuth: true // 需要前台登录
        }
      },
      
      // 用户中心 - 订单和电子票
      {
        path: 'front/user/orders',
        name: 'FrontUserOrders',
        component: () => import('@/views/front/user/OrderList.vue'),
        meta: { 
          title: '我的订单', 
          requiresAuth: false,
          requiresFrontAuth: true // 需要前台登录
        }
      },
      {
        path: 'front/user/order-detail',
        name: 'FrontUserOrderDetail',
        component: () => import('@/views/front/user/OrderDetail.vue'),
        meta: { 
          title: '订单详情', 
          requiresAuth: false,
          requiresFrontAuth: true // 需要前台登录
        }
      },
      {
        path: 'front/user/tickets',
        name: 'FrontUserTickets',
        component: () => import('@/views/front/user/TicketList.vue'),
        meta: { 
          title: '我的电子票', 
          requiresAuth: false,
          requiresFrontAuth: true // 需要前台登录
        }
      },
      {
        path: 'front/user/ticket-detail',
        name: 'FrontUserTicketDetail',
        component: () => import('@/views/front/user/TicketDetail.vue'),
        meta: { 
          title: '电子票详情', 
          requiresAuth: false,
          requiresFrontAuth: true // 需要前台登录
        }
      }
    ]
  },
  
  // 活动管理路由
  {
    path: '/event',
    component: () => import('@/views/event/List.vue'),
    name: 'EventList',
    meta: { 
      title: '活动列表', 
      requiresAuth: true
    }
  },
  {
    path: '/event/detail/:id',
    component: () => import('@/views/event/Detail.vue'),
    name: 'EventDetail',
    meta: { 
      title: '活动详情', 
      requiresAuth: true
    }
  },
  {
    path: '/event/create',
    component: () => import('@/views/event/Edit.vue'),
    name: 'EventCreate',
    meta: {
      title: '创建活动',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  {
    path: '/event/edit/:id',
    component: () => import('@/views/event/Edit.vue'),
    name: 'EventEdit',
    meta: {
      title: '编辑活动',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  {
    path: '/event/report/:id',
    component: () => import('@/views/report/EventReport'),
    name: 'EventReport',
    meta: {
      title: '活动统计',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  
  // 票种管理路由
  {
    path: '/ticket',
    name: 'TicketList',
    component: () => import('@/views/ticket/List.vue'),
    meta: {
      title: '票种管理',
      requiresAuth: true
    }
  },
  
  // 用户管理路由
  {
    path: '/user',
    name: 'UserList',
    component: () => import('@/views/user/List.vue'),
    meta: {
      title: '用户管理',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  
  // 会话管理路由
  {
    path: '/session/online',
    name: 'OnlineUsers',
    component: () => import('@/views/session/Online.vue'),
    meta: {
      title: '在线用户',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  
  // 日志管理路由
  {
    path: '/log/login',
    name: 'LoginLog',
    component: () => import('@/views/log/LoginLog.vue'),
    meta: {
      title: '登录日志',
      requiresAuth: true,
      requiresAdmin: true,
      keepAlive: false
    }
  },
  
  // 问卷管理路由
  {
    path: '/questionnaire/template-list',
    name: 'QuestionnaireTemplateList',
    component: () => import('@/views/questionnaire/TemplateList.vue'),
    meta: {
      title: '问卷模板管理',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  {
    path: '/questionnaire/template-edit/:id?',
    name: 'QuestionnaireTemplateEdit',
    component: () => import('@/views/questionnaire/TemplateEdit.vue'),
    meta: {
      title: '编辑问卷模板',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  {
    path: '/questionnaire/fill/:eventId',
    name: 'FillQuestionnaire',
    component: () => import('@/views/questionnaire/FillQuestionnaire.vue'),
    meta: {
      title: '填写问卷',
      requiresAuth: true
    }
  },
  
  // 报表统计路由
  {
    path: '/report/dashboard',
    name: 'ReportDashboard',
    component: () => import('@/views/report/Dashboard.vue'),
    meta: {
      title: '统计概览',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  {
    path: '/report/user-ranking',
    name: 'UserRanking',
    component: () => import('@/views/report/UserRanking.vue'),
    meta: {
      title: '用户活跃度排行',
      requiresAuth: true,
      requiresAdmin: true
    }
  },
  
  // 错误页面
  {
    path: '/403',
    name: '403',
    component: () => import('@/views/error/403.vue'),
    meta: { title: '403', requiresAuth: false }
  },
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 活动票务管理系统` : '活动票务管理系统'
  
  console.log(`路由导航: 从 ${from.path} 到 ${to.path}`)
  
  // 获取token和用户信息
  const token = localStorage.getItem('token')
  const frontToken = localStorage.getItem('frontToken') // 前台token
  let userRole = ''
  
  // 尝试解析用户角色
  try {
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      const userObj = JSON.parse(userInfo)
      userRole = userObj.role || ''
    }
  } catch (e) {
    console.error('解析用户信息失败', e)
  }
  
  // 判断是否是前台路由 - 以/front开头或根路径
  const isFrontRoute = to.path.startsWith('/front') || to.path === '/'
  
  // 检查是否明确允许匿名访问
  if (to.meta.allowAnonymous) {
    console.log('路由明确允许匿名访问，直接放行:', to.path)
    next()
    return
  }
  
  // 路由需要后台认证且不是前台路由
  if (to.meta.requiresAuth && !isFrontRoute) {
    // 未登录状态
    if (!token) {
      console.log('需要后台登录权限，重定向到登录页')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 需要管理员权限但用户不是管理员
    if (to.meta.requiresAdmin && userRole !== 'admin') {
      console.log('需要管理员权限，重定向到403页面')
      next({ path: '/403' })
      return
    }
    
    // 有token且权限满足
    console.log('后台权限验证通过，允许访问:', to.path)
    next()
    return
  }
  
  // 处理前台路由 - 前台路由不需要强制登录，但如果有requiresFrontAuth标记则需要验证前台token
  if (isFrontRoute && to.meta.requiresFrontAuth) {
    if (!frontToken) {
      console.log('需要前台登录权限，重定向到前台登录页')
      next({
        path: '/front/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }
  
  // 处理登录页面 - 已登录用户访问后台登录页
  if (to.path === '/login' && token) {
    console.log('已登录用户访问后台登录页，重定向到事件管理页面')
    
    // 如果有指定的redirect参数，优先使用该参数
    if (to.query.redirect) {
      next({ path: to.query.redirect })
    } else {
      next({ path: '/event' })
    }
    return
  }
  
  // 处理前台登录页面 - 已登录用户访问前台登录页
  if (to.path === '/front/login' && frontToken) {
    console.log('已登录用户访问前台登录页，重定向到前台首页')
    
    // 如果有指定的redirect参数，优先使用该参数
    if (to.query.redirect) {
      next({ path: to.query.redirect })
    } else {
      next({ path: '/' })
    }
    return
  }
  
  // 其他页面正常访问
  console.log('正常访问页面:', to.path)
  next()
})

// 添加全局路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  // 尝试恢复导航或重定向到错误页面
  const pathError = window.location.pathname
  console.error(`路径 ${pathError} 加载失败，错误:`, error.message)
  
  // 仅对活动相关路由进行特殊处理
  if (pathError.includes('/event')) {
    console.log('正在尝试恢复活动管理路由...')
    // 可以在这里添加重定向逻辑或重新加载组件
    
    // 如果是组件加载失败，可以提示用户刷新页面
    if (error.message.includes('Failed to fetch dynamically imported module')) {
      alert('页面加载失败，请刷新页面重试')
    }
  }
})

export default router 
